﻿using Common.CAP;
using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Common.Cap.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加Cap服务
        /// </summary>
        /// <param name="services"></param> 
        /// <returns></returns>
        public static IServiceCollection AddCapConfig(this IServiceCollection services, string section = "Rabbitmq")
        { 
            var rabbitMQOptions = ServiceProviderServiceExtensions.GetRequiredService<IConfiguration>(services.BuildServiceProvider()).GetSection(section).Get<RabbitMQOptions>();
            services.AddCap(x =>
            {
                x.UseMySql("server=192.168.113.128;port=3306;database=capdb;user=root;password=123456");
                x.UseRabbitMQ(opt =>
                {
                    //opt.HostName = "192.168.113.128";
                    //opt.Port = 5672;
                    //opt.UserName = "admin";
                    //opt.Password = "123456";
                    ////opt.PublishConfirms = true;
                    //opt.VirtualHost = "/";
                    opt.HostName = rabbitMQOptions.HostName;
                    opt.Port = rabbitMQOptions.Port;
                    opt.UserName = rabbitMQOptions.UserName;
                    opt.Password = rabbitMQOptions.Password;
                    opt.PublishConfirms = rabbitMQOptions.PublishConfirms;
                    opt.VirtualHost = rabbitMQOptions.VirtualHost;
                });
                x.UseDashboard();
                //成功消息的过期时间（秒）
                x.SucceedMessageExpiredAfter = 10 * 24 * 3600;
                x.FailedRetryCount = 3;
            });
            services.AddSingleton<OrderService>();
            services.AddSingleton<TestHandler>();
            return services;
        }
    }
}
